package org.loofer.ext.utils;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.message.BasicNameValuePair;
import org.apache.log4j.spi.LocationInfo;

public final class UrlUtils {
    private UrlUtils() {
    }

    public static boolean isNetworkUrl(String url) {
        if (url == null || url.length() == 0) {
            return false;
        }
        if (isHttpUrl(url) || isHttpsUrl(url)) {
            return true;
        }
        return false;
    }

    public static boolean isHttpUrl(String url) {
        return url != null && url.length() > 6 && StringUtils.startsWithIgnoreCase(url, "http://");
    }

    public static boolean isHttpsUrl(String url) {
        return url != null && url.length() > 7 && StringUtils.startsWithIgnoreCase(url, "https://");
    }

    public static String buildUrl(String host, Map<String, Object> params) {
        if (params == null || params.size() == 0) {
            return host;
        }
        ArrayList<NameValuePair> paramPairs = new ArrayList(params.size());
        for (String key : params.keySet()) {
            paramPairs.add(new BasicNameValuePair(key, String.valueOf(params.get(key))));
        }
        StringBuilder url = new StringBuilder(host);
        if (paramPairs.size() > 0) {
            url.append(url.indexOf(LocationInfo.NA) == -1 ? LocationInfo.NA : "&").append(URLEncodedUtils.format(paramPairs, "UTF-8"));
        }
        return url.toString();
    }

    public static Map<String, Object> getParams(String url) {
        Map<String, Object> params = new LinkedHashMap();
        if (!StringUtils.isEmpty(url) && url.contains(LocationInfo.NA)) {
            for (String param : url.substring(url.indexOf(63) + 1).split("&")) {
                String[] entry = param.split("=");
                params.put(entry[0], entry.length == 2 ? entry[1] : "");
            }
        }
        return params;
    }

    public static String getHost(String url) {
        if (StringUtils.isEmpty(url) || url.indexOf(63) <= 0) {
            return url;
        }
        return url.substring(0, url.indexOf(63));
    }

    public static String getFileName(String url) {
        return FileUtils.getFileName(url);
    }

    public static String removeParam(String url, String paramKey) {
        String host = getHost(url);
        Map<String, Object> params = getParams(url);
        params.remove(paramKey);
        return buildUrl(host, params);
    }

    public static String removeParams(String url, Set<String> paramKeys) {
        String host = getHost(url);
        Map<String, Object> params = getParams(url);
        for (String key : paramKeys) {
            params.remove(key);
        }
        return buildUrl(host, params);
    }
}
